var randomstring = require('randomstring')
var config = require('../config')
var qs = require('querystring')
var md5 = require('md5')
var convert = require('xml-js')

exports.getNoncestr = () => {
    return randomstring.generate(32)
}

exports.getSign = (M) => {
    // {"appid":"wx100749d4612ea385","mch_id":"1448624302","nonce_str":"XKphAOlBD35ip5Fqlbjrz6ClKyGjrThs","body":"肥宅水","out_trade_no":"sh2003____01","total_fee":1,"notify_url":"https://walter666.cn/wxpay/notify","trade_type":"NATIVE"}  
    // 将集合M内非空参数值的参数按照参数名ASCII码从小到大排序
    // 1.1 获取到有哪些key值
    const keys = Object.keys(M) // ["appid","mch_id","nonce_str","body","out_trade_no","total_fee","notify_url","trade_type"]
    // 1.2 排序
    const sortKeys = keys.sort() // ["appid","body","mch_id","nonce_str","notify_url","out_trade_no","total_fee","trade_type"]
    // 1.3 按照排序后的顺序 重组 对象
    const obj = {}
    sortKeys.forEach(item => {
      obj[item] = M[item]
    }) 
    console.log(obj)
    // {"appid":"wx100749d4612ea385","body":"肥宅水","mch_id":"1448624302","nonce_str":"TVNLDUU43JnEzqy303G3d9dqx6LS3aoa","notify_url":"https://walter666.cn/wxpay/notify","out_trade_no":"sh2003____01","total_fee":1,"trade_type":"NATIVE"}
    // 使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串stringA。
  //   const stringA = qs.stringify(obj) // appid=wx100749d4612ea385&body=%E8%82%A5%E5%AE%85%E6%B0%B4&mch_id=1448624302&nonce_str=yBFB5ZhWgYRFlw3wpejfHrkI9SMvIri8¬ify_url=https%3A%2F%2Fwalter666.cn%2Fwxpay%2Fnotify&out_trade_no=sh2003____01&total_fee=1&trade_type=NATIVE
    const stringA = qs.stringify(obj, null, null, {
        encodeURIComponent (value) { // 不转义
          return  decodeURIComponent(value)
        }// appid=wx100749d4612ea385&body=肥宅水&mch_id=1448624302&nonce_str=us8a5HqicrhgSgiv2UZE63LWM6TTKAyU¬ify_url=https://walter666.cn/wxpay/notify&out_trade_no=sh2003____01&total_fee=1&trade_type=NATIVE
    })
    // 在stringA最后拼接上key得到stringSignTemp字符串
    const stringSignTemp = stringA + '&key=' + config.key
    // 并对stringSignTemp进行MD5运算
    const stringSignTempMd5 = md5(stringSignTemp)
    // 得到的字符串所有字符转换为大写
    const signValue = stringSignTempMd5.toUpperCase()
    return signValue
}

exports.getXml = (M, sign) => {
    /**
     * 外部包裹xml节点，key值为 标签名，value值为 值
    <xml>
        <appid>wxd930ea5d5a258f4f</appid>
        <mch_id>10000100</mch_id>
        <device_info>1000</device_info>
        <body>test</body>
        <nonce_str>ibuaiVcKdpRxkhJA</nonce_str>
        <sign>9A0A8659F005D6984697E2CA0A9CF3B7</sign>
    </xml>
     */
    const xmlObj = {
        xml: {
            ...M,
            sign
        }
    }
    /**
     * {
      xml:{
            "appid":"wx100749d4612ea385",
            "mch_id":"1448624302",
            "nonce_str":"IPh1vaIDmHp9HAegDVO4z8OvmOG1lQTv",
            "body":"肥宅水",
            "out_trade_no":"sh2003____01",
            "total_fee":1,
            "notify_url":"https://walter666.cn/wxpay/notify",
            "trade_type":"NATIVE",
            "sign":"98885AC4FBADCA180009D64CF14C21B7"
        }
     * }
     */
    const xml = convert.js2xml(xmlObj, {
      compact: true // 无论输入对象是在紧凑的形式或没有。默认情况下，输入应为非紧凑格式。
    })
    /**
     * <xml>
     * <appid>wx100749d4612ea385</appid>
     * <mch_id>1448624302</mch_id>
     * <nonce_str>3A4sgTwOlxd7xAb8jxnuQLpxlrhxAqPt</nonce_str>
     * <body>肥宅水</body>
     * <out_trade_no>sh2003____01</out_trade_no>
     * <total_fee>1</total_fee>
     * <notify_url>https://walter666.cn/wxpay/notify</notify_url>
     * <trade_type>NATIVE</trade_type>
     * <sign>E2FB7E6803EBB1C642C06CAC8D93AAB5</sign>
     * </xml>
     */
    return xml
}

exports.xml2js = (xml) => {
    
    // const result = convert.xml2js(xml)
    /**
     * {"elements":[{"type":"element","name":"xml","elements":[{"type":"element","name":"return_code","elements":[{"type":"cdata","cdata":"SUCCESS"}]},{"type":"element","name":"return_msg","elements":[{"type":"cdata","cdata":"OK"}]},{"type":"element","name":"appid","elements":[{"type":"cdata","cdata":"wx100749d4612ea385"}]},{"type":"element","name":"mch_id","elements":[{"type":"cdata","cdata":"1448624302"}]},{"type":"element","name":"nonce_str","elements":[{"type":"cdata","cdata":"K05jleeNgvG51I0B"}]},{"type":"element","name":"sign","elements":[{"type":"cdata","cdata":"1B5B298DBE101FA7189D69520C1DD423"}]},{"type":"element","name":"result_code","elements":[{"type":"cdata","cdata":"SUCCESS"}]},{"type":"element","name":"prepay_id","elements":[{"type":"cdata","cdata":"wx1715020111910494f1d1155613fb420000"}]},{"type":"element","name":"trade_type","elements":[{"type":"cdata","cdata":"NATIVE"}]},{"type":"element","name":"code_url","elements":[{"type":"cdata","cdata":"weixin://wxpay/bizpayurl?pr=W9ArzeS00"}]}]}]}
     */
    const result = convert.xml2js(xml, {
        compact: true,
        textKey: 'value',
        cdataKey: 'value'
    })
    /**
     * {"xml":{"return_code":{"value":"SUCCESS"},"return_msg":{"value":"OK"},"appid":{"value":"wx100749d4612ea385"},"mch_id":{"value":"1448624302"},"nonce_str":{"value":"hnxNSvCn2LcXo9if"},"sign":{"value":"84C15C2F2334D92B707EA96015C58B46"},"result_code":{"value":"SUCCESS"},"prepay_id":{"value":"wx1715045631139594f1d11556dda6b50000"},"trade_type":{"value":"NATIVE"},"code_url":{"value":"weixin://wxpay/bizpayurl?pr=kttzKHc00"}}}
     */
    // 获取到所有的key值
    const keys= Object.keys(result.xml)
    const obj = {}
    keys.forEach(item => {
        obj[item] = result.xml[item].value
    })
    /**
     * {"return_code":"SUCCESS","return_msg":"OK","appid":"wx100749d4612ea385","mch_id":"1448624302","nonce_str":"ZgfKwKQenWPMpzHm","sign":"CAD8E9388E6B83BEC6361CE894DC31C0","result_code":"SUCCESS","prepay_id":"wx1715084413850594f1d115568d328b0000","trade_type":"NATIVE","code_url":"weixin://wxpay/bizpayurl?pr=enzm8Ga00"}
     */
    return obj
}